<?php

/**
 * This is the model class for table "{{users}}".
 *
 * The followings are the available columns in table '{{users}}':
 * @property integer $id
 * @property string $ukey
 * @property string $password
 * @property string $salt
 * @property string $email
 * @property string $status
 * @property integer $date_created
 * @property string $type
 * @property string $firstname
 * @property string $lastname
 * @property string $address
 * @property string $address2
 * @property string $city
 * @property string $postal_code
 * @property string $country
 * @property string $fax
 * @property string $photo
 * @property string $gender
 * @property string $occupation
 * @property string $note
 * @property string $business_name
 * @property string $business_id
 * @property string $business_type
 * @property string $business_description
 * @property string $business_logo
 * @property string $business_slogan
 * @property string $website
 * @property string $tax_id
 * @property string $contract_start
 * @property string $contract_end
 * @property integer $author_id
 * @property string $facebook
 * @property string $twitter
 * @property string $gplus
 * @property string $instagram
 * @property int $birthday 
 * @property string $mobile_phone 
 * @property string $home_phone
 * @property string $office_phone 
 * @property string $latitude 
 * @property string $longitude
 */
class Users extends CActiveRecord
{

    const SUPER_ADMIN      = 1;
    const TYPE_ADMIN       = 'Admin';
    const TYPE_BUSINESS    = 'BizUser';
    const TYPE_STAFF       = 'Staff';
    const TYPE_CUSTOMER    = 'Customer';
    const TYPE_CONCIERGE   = 'Concierge';
    const STATUS_ACTIVE    = 'active';
    const STATUS_BLOCK     = 'block';
    const STATUS_TRIAL     = 'trial';
    const MOBILE           = 0;
    const HOME_PHONE       = 1;
    const OFFICE_PHONE     = 2;
    // For Ukey
    const PREFIX_ADMIN     = 'ADM';
    const PREFIX_BUSINESS  = 'BSN';
    const PREFIX_STAFF     = 'STF';
    const PREFIX_CUSTOMER  = 'CUS';
    const PREFIX_CONCIERGE = 'CON';
    //payment percent
    const PAYMENT_PERCENT  = 70;

    public $repassword; //Repeat Password
    public $new_pass; //New password
    public $old_pass; //Old password
    public $renewpass; //Repeat New Password
    public $verifyCode; // Capcha
    public $staff_group;
    public $biz_id; // Business ID

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Users the static model class
     */

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return mixed A single active record of current user
     */
    public static function getCurrentUser()
    {
        return Users::model()->findByPk(Yii::app()->user->getId());
    }

    /**
     * @param $email
     * @return Users
     */
    public function findByEmail($email)
    {
        $crite = new CDbCriteria();

        $crite->compare('email', $email);
        $crite->compare('type', Users::TYPE_CUSTOMER);

        $user = Users::model()->find($crite);

        if (NULL == $user)
        {
            return FALSE;
        }
        else
        {
            return $user;
        }
    }

    /**
     * Use at HuserinfoForm.php
     * @param type $email
     */
    public static function find_customer_by_email($email)
    {

        $crite = new CDbCriteria();
        $crite->compare('email', $email);
        $crite->compare('type', Users::TYPE_CUSTOMER);

        $user = Users::model()->find($crite);

        if (NULL == $user)
        {
            return FALSE;
        }
        else
        {
            return $user;
        }
    }

    public function verifyPassword($password)
    {
        return ($this->hashPassword($password, $this->salt) == $this->password);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{users}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('nickname, description', 'safe'),
            array('nickname, description', 'safe', 'on' => 'profile_' . self::TYPE_STAFF),
            array('email', 'required'),
//            array('ukey', 'unique'),
            array('email', 'email'),
//            array('email', 'unique','except'=>'clone_staff'),
            array('author_id', 'numerical'),
            array('password, new_pass', 'length', 'min' => 6),
            array('firstname, lastname, password, repassword, social_source', 'length', 'max' => 32),
            array('status, postal_code, gender, business_id', 'length', 'max' => 20),
            array('occupation, type, address, address2, business_name, business_type, website, contract_start, 
                contract_end, facebook, twitter, gplus, instagram',
                'length', 'max' => 255
            ),
            array('latitude, longitude', 'length', 'max' => 200),
            array('social_token,social_id', 'length', 'max' => 100),
            array('social_token,social_id,social_source', 'required', 'on' => 'signup-frontend-social'),
            array('city, tax_id, fax', 'length', 'max' => 255),
            //Change password
            array('old_pass, new_pass, renewpass', 'required', 'on' => 'changepassword'),
            array('old_pass', 'checkOldPassword', 'on' => 'changepassword'),
            array('renewpass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'changepassword'),
            //Forgot password
            array('email', 'required', 'on' => 'forgotpwd'),
            array('email', 'email', 'on' => 'forgotpwd'),
//            array('renewpass', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'forgotpass'),
            //Reset password
            array('new_pass, repassword', 'required', 'on' => 'resetpwd'),
            array('repassword, new_pass', 'length', 'min' => 6, 'on' => 'resetpwd'),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'message' => 'Password repeated is incorrect', 'on' => 'resetpwd'),
            //Change Email
            array('newmail, renewmail', 'required', 'on' => 'changeemail'),
            array('renewmail', 'compare', 'compareAttribute' => 'newmail', 'on' => 'changeemail'),
            array('newmail, renewmail', 'email', 'on' => 'changeemail'),
            //Create customer in Appointment
            array('firstname, lastname, home_phone', 'required', 'on' => 'customer-appt'),
            /**
             * Create User
             */
            //Biz owner
            array('email, new_pass, repassword, business_name, office_phone',
                'required',
                'on' => 'create_' . self::TYPE_BUSINESS
            ),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'create_' . self::TYPE_BUSINESS),
            array('email, business_name, office_phone',
                'required',
                'on' => 'edit_' . self::TYPE_BUSINESS
            ),
            array('new_pass',
                'safe',
                'on' => 'edit_' . self::TYPE_BUSINESS
            ),
            //Staff
            array(
                'email, firstname, lastname, new_pass, repassword, mobile_phone',
                'required',
                'on' => 'create_' . self::TYPE_STAFF
            ),
            array('repassword', 'compare', 'compareAttribute' => 'new_pass', 'on' => 'create_' . self::TYPE_STAFF),
            array(
                'email, firstname, lastname, mobile_phone',
                'required',
                'on' => 'edit_' . self::TYPE_STAFF
            ),
            array(
                'new_pass',
                'unsafe',
                'on' => 'edit_' . self::TYPE_STAFF
            ),
            // Admin
            array(
                'email, firstname, lastname',
                'required',
                'on' => 'edit_' . self::TYPE_ADMIN
            ),
            array(
                'email, new_pass, firstname, lastname, status',
                'required',
                'on' => 'create_' . self::TYPE_ADMIN
            ),
            array(
                'email, new_pass, firstname, lastname',
                'unsafe',
                'on' => 'edit_' . self::TYPE_ADMIN
            ),
            // Customer
            array(
                'email, firstname, lastname',
                'required',
                'on' => 'create_' . self::TYPE_CUSTOMER
            ),
            array(
                'email, firstname, lastname, mobile_phone',
                'required',
                'on' => 'validate_address, edit_' . self::TYPE_CUSTOMER
            ),
            array(
                'address, postal_code',
                'required', 'on' => 'validate_address'
            ),
            array(
                'email, new_pass',
                'unsafe',
                'on' => 'validate_address, edit_' . self::TYPE_CUSTOMER
            ),
            /**
             * Quy định v�? các trư�?ng dữ liệu của User không được tự ý sửa
             */
            // Bussiness
            array('id, password, email, type, author_id, date_created,business_name',
                'unsafe', 'on' => 'profile_' . self::TYPE_BUSINESS),
            array('business_name, office_phone',
                'required',
                'on' => 'profile_' . self::TYPE_BUSINESS
            ),
            array(
                'id, password, email, type, author_id, date_created',
                'unsafe',
                'on' => 'profile_' . self::TYPE_STAFF
            ),
            array(
                'id, password, email, type, author_id, date_created',
                'unsafe',
                'on' => 'profile_' . self::TYPE_ADMIN
            ),
            array('nickname, description', 'safe', 'on' => 'profile_' . self::TYPE_STAFF),
            array(
                'id, password, email, type, author_id, date_created',
                'unsafe',
                'on' => 'profile_' . self::TYPE_CUSTOMER
            ),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('profile,repassword, note, facebook, twitter, gplus, instagram, office_phone, home_phone, mobile_phone, country, photo, business_description, business_slogan', 'safe'),
            array('id, firstname, lastname, gender, occupation, address, address2, city, country, postal_code, type, status, business_id, business_name, business_type, business_logo, business_description, business_slogan, tax_id, website, email, author_id, date_created, facebook, twitter, gplus, instagram, latitude , longitude, social_token, social_id,social_source', 'safe', 'on' => 'search'),
            array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'on' => 'signup'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        $relations       = parent::relations();
        $relations['id'] = array(
            self::HAS_MANY, 'Changeemail', 'admin_id',
        );

        $relations['gallery'] = array(
            self::HAS_MANY, 'BusinessGallery', 'business_id',
        );

        $relations['author'] = array(
            self::BELONGS_TO, 'Users', 'author_id',
        );
        $relations['branch'] = array(
            self::HAS_MANY, 'Users', array('id' => 'author_id'),
        );
        $relations['oders']  = array(
            self::HAS_MANY, 'Orders', 'staff_id',
        );

        $relations['todayTimeClock'] = array(
            self::HAS_MANY, 'TimeClock', 'user_id',
            'condition' => 'date=:d',
            'params'    => array(':d' => date('Y-m-d', time()))
        );

        $relations['customers']            = array(
            self::HAS_MANY, 'Customer', 'user_id',
        );
        $relations['business']             = array(
            self::HAS_ONE, 'Business', 'user_id',
        );
        $relations['service']              = array(
            self::HAS_ONE, 'ServicePoints', 'business_id',
        );
//        $relations['services'] = array(
//            self::HAS_MANY, 'Service', 'author_id',
//            'condition' => 'type=:t',
//            'params' => array(':t' => Service::TYPE_SERVICE)
//        );
        $relations['merchantCats']         = array(
            self::HAS_MANY, 'BusinessCategoryUser', 'biz_id'
        );
        //for staff label
        $relations['label']                = array(
            self::HAS_ONE, 'GroupUser', 'user_id',
        );
        $relations['area']                 = array(
            self::HAS_MANY, 'AreaUser', 'user_id',
        );
        $relations['taxs']                 = array(
            self::HAS_MANY, 'Tax', 'author_id',
        );
        $relations['redemptioncount']      = array(
            self::STAT, 'Redeem', 'biz_id',
        );
        $relations['rePendingcount']       = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => "status=0 and (expired_date='0000-00-00 00:00:00' OR expired_date >= '" . date('Y-m-d H:i:s', time()) . "')",
        );
        $relations['reRedeemedcount']      = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => 'status=1 and payment=0',
        );
        $relations['rePaidcount']          = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => 'status=1 and payment=1',
        );
        $relations['reTotalAmount']        = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => 'status=1', 'select'    => 'SUM(amount)'
        );
        $relations['reTotalPaymentAmount'] = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => 'status=1', 'select'    => 'SUM(payment_amount)'
        );
        $relations['reTotalPaidAmount']    = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => 'status=1 and payment=1', 'select'    => 'SUM(payment_value)'
        );
        $relations['reExpiredcount']       = array(
            self::STAT, 'Redeem', 'biz_id',
            'condition' => "status=0 and expired_date<>'0000-00-00 00:00:00' and expired_date <'" . date('Y-m-d H:i:s', time()) . "'",
        );

        return $relations;
    }

    public static function getNameByUkey($ukey)
    {
        $crite         = new CDbCriteria();
        $crite->select = array('ukey', 'lastname', 'firstname', 'business_name');
        $crite->compare('ukey', $ukey);

        $user = Users::model()->find($crite);
        if (NULL == $user)
        {
            return FALSE;
        }
        return $user->name;
    }

    public function getTotalTax()
    {
        $criteria            = new CDbCriteria();
        $criteria->select    = array('value', 'value');
        $criteria->condition = 'author_id=:author_id';
        $criteria->params    = array(':author_id' => $this->id);

        $taxs = Tax::model()->findAll($criteria);

        $total = 0;

        if (!$taxs)
        {
            return 0;
        }
        else
        {
            foreach ($taxs as $tax)
            {
                $total+=floatval($tax->value);
            }

            return $total;
        }
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id'                   => 'ID',
            'ukey'                 => Yii::t('user', 'User Key'),
            'password'             => Yii::t('user', 'Password'),
            'salt'                 => Yii::t('user', 'Salt'),
            'email'                => Yii::t('user', 'Email'),
            'type'                 => Yii::t('user', 'Type'),
            'date_created'         => Yii::t('user', 'Date Created'),
            'new_pass'             => Yii::t('user', 'Password'),
            'old_pass'             => Yii::t('user', 'Old password'),
            'repassword'           => Yii::t('user', 'Password repeat'),
            'renewpass'            => Yii::t('user', 'Repeat new password'),
            'verifyCode'           => Yii::t('user', 'Verify Code'),
            'address'              => Yii::t('user', 'Address'),
            'home_phone'           => Yii::t('user', 'Home Phone'),
            'mobile_phone'         => Yii::t('user', 'Mobile Phone'),
            'office_phone'         => Yii::t('user', 'Office Phone'),
            'fax'                  => Yii::t('user', 'Fax Number'),
            'firstname'            => Yii::t('user', 'First Name'),
            'lastname'             => Yii::t('user', 'Last Name'),
            'address2'             => Yii::t('user', 'Address 2'),
            'city'                 => Yii::t('user', 'Area'),
            'country'              => Yii::t('user', 'Country'),
            'photo'                => ($this->type == self::TYPE_BUSINESS) ? 'Merchant Logo' : 'Photo',
            'status'               => Yii::t('user', 'Status'),
            'country'              => Yii::t('user', 'Country'),
            'gender'               => Yii::t('user', 'Gender'),
            'occupation'           => Yii::t('user', 'Occupation'),
            'note'                 => Yii::t('user', 'Note'),
            'business_name'        => Yii::t('user', 'Merchant Name'),
            'business_id'          => Yii::t('user', 'Merchant'),
            'business_type'        => Yii::t('user', 'Merchant Category'),
            'business_description' => Yii::t('user', 'Merchant Description'),
            'business_slogan'      => Yii::t('user', 'Merchant Slogan'),
            'website'              => Yii::t('user', 'Website'),
            'tax_id'               => Yii::t('user', 'Tax ID'),
            'contract_start'       => Yii::t('user', 'Contract Start Date'),
            'contract_end'         => Yii::t('user', 'Contract End Date'),
            'author_id'            => ($this->type == self::TYPE_CUSTOMER) ? 'Staff' : 'Merchant',
            'facebook'             => Yii::t('user', 'Facebook ID/URL'),
            'twitter'              => Yii::t('user', 'Twitter ID/URL'),
            'gplus'                => Yii::t('user', 'Google+ ID/URL'),
            'instagram'            => Yii::t('user', 'Instagram ID/URL'),
            'longitude'            => Yii::t('user', 'Longitude'),
            'latitude'             => Yii::t('user', 'Latitude'),
            'author.name'          => Yii::t('user', 'Manager Name'),
            'nickname'             => 'Display Name',
            'social_source'        => Yii::t('user', 'Social source'),
            'social_id'            => Yii::t('user', 'Social ID'),
            'social_token'         => Yii::t('user', 'Social token'),
        );
    }

    public function admin_filter()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('type', self::TYPE_ADMIN);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function business_filter()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('type', self::TYPE_BUSINESS);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function staff_filter()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('type', self::TYPE_STAFF);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function customer_filter()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('type', self::TYPE_CUSTOMER);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('salt', $this->salt, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('type', $this->type, true);
        $criteria->compare('status', $this->status, true);
        $criteria->compare('date_created', $this->date_created, true);
        $criteria->compare('firstname', $this->firstname, true);
        $criteria->compare('lastname', $this->lastname, true);
        $criteria->compare('address', $this->address, true);
        $criteria->compare('address2', $this->address2, true);
        $criteria->compare('city', $this->city, true);
        $criteria->compare('postal_code', $this - postal_code, true);
        $criteria->compare('country', $this->country, true);
        $criteria->compare('home_phone', $this->home_phone, true);
        $criteria->compare('mobile_phone', $this->mobile_phone, true);
        $criteria->compare('office_phone', $this->office_phone, true);
        $criteria->compare('photo', $this->photo, true);
        $criteria->compare('gender', $this->gender, true);
        $criteria->compare('occupation', $this->occupation, true);
        $criteria->compare('note', $this->note, true);
        $criteria->compare('business_name', $this->business_name, true);
        $criteria->compare('business_id', $this->business_id, true);
        $criteria->compare('business_type', $this->business_type, true);
        $criteria->compare('business_description', $this->business_description, true);
        $criteria->compare('business_slogan', $this->business_slogan, true);
        $criteria->compare('website', $this->website, true);
//        $criteria->compare('tax_id', $this->tax_id, true);
        $criteria->compare('contract_start', $this->contract_start, true);
        $criteria->compare('contract_end', $this->contract_end, true);
        $criteria->compare('author_id', $this->author_id, true);
        $criteria->compare('latitude', $this->latitude, true);
        $criteria->compare('longitude', $this->longitude, true);
        $criteria->compare('social_token', $this->social_token, true);
        $criteria->compare('social_id', $this->social_id, true);
        $criteria->compare('social_source', $this->social_source, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * 
     */
    public static function getLastMerchant()
    {
        $criteria = new CDbCriteria();

        $criteria->condition = 'status=:status AND type=:type';
        $criteria->params    = array(':status' => Users::STATUS_ACTIVE, ':type' => Users::TYPE_BUSINESS);
        $criteria->order     = 'id DESC';

        return Users::model()->find($criteria);
    }

    /**
     * Checks if the given password is correct.
     * @param string the password to be validated
     * @return boolean whether the password is valid
     */
    public function validatePassword($password)
    {
//        return true;
        return ($this->hashPassword($password, $this->salt) == $this->password);
    }

    public function validateRole($role)
    {
        return ($role == $this->type);
    }

    /**
     * Checks if the given password is correct.
     * @param string the password to be validated
     * @return boolean whether the password is valid
     */
    public function checkOldPassword($attribute)
    {
        if ($this->hashPassword($this->{$attribute}, $this->salt) === $this->password)
            return TRUE;
        else
        {
            $this->addError($attribute, Yii::t('adminuser', '{object} is incorrect', array(
                        '{object}' => $this->getAttributeLabel($attribute),
            )));
            return FALSE;
        }
    }

    /**
     * Generates the password hash.
     * @param string password
     * @param string salt
     * @return string hash
     */
    public function hashPassword($password, $salt)
    {
        return md5($salt . $password);
    }

    public static function getTypeOfUserByID($id)
    {
        $user = Users::model($id);
        if ($user->type == Users::TYPE_ADMIN)
        {
            return self::TYPE_ADMIN;
        }
        else if ($user->type == Users::TYPE_BUSINESS)
        {
            return self::TYPE_BUSINESS;
        }
        else
        {
            return self::TYPE_STAFF;
        }
    }

    /**
     * Generates a salt that can be used to generate a password hash.
     * @return string the salt
     */
    public function generateSalt()
    {
        return uniqid('', true);
    }

    public function beforeSave()
    {
        if (parent::beforeSave())
        {
            if ($this->new_pass != '')
            {
                $this->salt     = $this->generateSalt();
                $this->password = $this->hashPassword($this->new_pass, $this->salt);
            }

            return TRUE;
        }
        else
            return FALSE;
    }

    protected function afterSave()
    {

        if (parent::afterSave())
        {
            $auth = Yii::app()->authManager;

            // Xóa các quy�?n đã gán trước đây đi
            if ($auth->getAuthAssignments($this->id))
                foreach ($auth->getAuthAssignments($this->id) as $item)
                    $auth->revoke($item->itemName, $this->id);

            // Gán quy�?n mới 
            $auth->assign($this->type, $this->id);

            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    function getObjectName()
    {
        return $this->email;
    }

    public function getNameAuthor()
    {

        return( ($this->firstname != NULL) ? $this->firstname : '' ) . ' ' .
                (($this->lastname != NULL) ? $this->lastname : '');
    }

    /**
     * 
     * @param type $act name of action
     * @param type $con name of controller
     * @return boolean
     */
    static function checkAccess($act, $con)
    {
//        return TRUE;
        $act = ucfirst($act);
        $con = ucfirst($con);
        //CVarDumper::dump($act);
        if (Yii::app()->user->checkAccess("$con.*"))
            return TRUE;

        if (Yii::app()->user->checkAccess("$con.$act"))
            return TRUE;

        return FALSE;
    }

    public static function getArrayType()
    {
        return array(
            self::TYPE_ADMIN    => 'Administrator',
            self::TYPE_BUSINESS => 'Merchant',
            self::TYPE_STAFF    => 'Staff',
            self::TYPE_CUSTOMER => 'Customer',
        );
    }

    public static function getArrayStatus()
    {
        return array(
            self::STATUS_ACTIVE => 'Active',
            self::STATUS_BLOCK  => 'Block',
        );
    }

    public static function getAvailableStatus()
    {
        return array(
            self::STATUS_ACTIVE => 'Active',
            self::STATUS_TRIAL  => 'Trial',
        );
    }

    public static function getArrayMerchantStatus()
    {
        return array(
            self::STATUS_ACTIVE => 'Active',
            self::STATUS_BLOCK  => 'Block',
            self::STATUS_TRIAL  => 'Trial',
        );
    }

//
//    public static function getBussinessType()
//    {
//        return array(
//            'CORPORATION' => 'CORPORATION',
//            'AGENCY' => 'AGENCY',
//            'DBA' => 'DBA',
//            'LLC' => 'LLC',
//            'INCORPORATE' => 'INCORPORATE',
//            'OTHER' => 'OTHER',
//        );
//    }

    /**
     * use at profile merchant
     * @return mixed a url with 'http://' or not
     */
    public function getPublicWebsite()
    {

        if (!$this->website OR $this->website == '')
            return FALSE;

        if (FALSE == strpos('http', $this->website))
        {
            return 'http://' . $this->website;
        }
        else
        {
            return $this->website;
        }
    }

    public static function getContries()
    {
        return array(
            'VN'   => 'Viet Nam',
            'SING' => 'Singapore',
            'LAOS' => 'Laos',
        );
    }

    public static function getGender()
    {
        return array(
            NULL => Yii::t('main', 'Other'),
            'M'  => Yii::t('main', 'Male'),
            'F'  => Yii::t('main', 'Female'),
        );
    }

    public function getAvartBySize($width, $height)
    {

        if (!$this->photo)
        {
            return Yii::app()->controller->assetDir . 'img/avatar-blank.jpg';
        }


        if (strstr($this->photo, 'http') != FALSE)
        {
            return $this->photo;
        }

        $file = Yii::getPathOfAlias('webroot') . '/' . $this->photo;
        $path = Yii::getPathOfAlias('webroot') . '/files/user/';

        if (!file_exists($file))
        {
            return Yii::app()->controller->assetDir . 'img/avatar-blank.jpg';
        }

        $path_parts = pathinfo($file);

        $extesion  = $path_parts['extension'];
        $file_name = $path_parts['filename'] . "_w" . $width . 'h' . $height . '.' . $extesion;

        if (!file_exists($path . $file_name) AND ! is_file($path . $file_name))
        {

            $thumb = Yii::app()->phpThumb->create($file);
            $thumb->adaptiveResize($width, $height);
            $thumb->save($path . '/' . $file_name);
        }

        return Yii::app()->baseUrl . '/files/user' . '/' . $file_name;
    }

    public function getPublicPhoto()
    {
        if ($this->photo)
        {
            if (strstr($this->photo, 'http') !== FALSE)
            {
                return $this->photo;
            }
            else
            {
                return Yii::app()->baseUrl . "/" . $this->photo;
            }
        }
        else
        {
            return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
        }
    }

    public function getBizLogo()
    {
        if ($this->business_logo)
            return Yii::app()->baseUrl . "/" . $this->business_logo;
        else
            return Yii::app()->controller->assetDir . '/img/logo_small.png';
    }

    public function getPublicBusinessLogo()
    {
        if ($this->business_logo)
            return Yii::app()->baseUrl . "/" . $this->business_logo;
        else
            return Yii::app()->controller->assetDir . '/img/no-image.png';
    }

    public function getPhone()
    {
        if ($this->mobile_phone != NULL)
            return $this->mobile_phone;
        if ($this->home_phone != NULL)
            return $this->home_phone;
        if ($this->office_phone != NULL)
            return $this->office_phone;
    }

    public function getPhoneAndType()
    {
        if ($this->mobile_phone != NULL)
            return Users::MOBILE;
        if ($this->home_phone != NULL)
            return Users::HOME_PHONE;
        if ($this->office_phone != NULL)
            return Users::OFFICE_PHONE;
    }

    /**
     * @return List of Appointment  that user belong to
     */
    public function getListAppoint()
    {

        $criteria            = new CDbCriteria();
        $criteria->condition = 'customer_id=:cus_id';
        $criteria->params    = array(':cus_id' => $this->id);
        $criteria->order     = 'apt_id DESC';

        $list = AptCustomer::model()->findAll($criteria);

        if ($list == NULL)
        {
            return array();
            Yii::app()->end();
        }
        else
        {
            $arr = array();
            foreach ($list as $v)
            {

                $arr[] = array(
                    'id_appoint'   => $v->apt_id,
                    'service_name' => $v->appt->service->s_name,
                    'date'         => date('D M d Y', $v->appt->date),
                    'start_time'   => $v->appt->start_time,
                    'appoint_new'  => $v->appt->isProcess,
                );
            }
            return $arr;
        }
    }

    public function getStatusLabel()
    {
        if (!$this->hasAttribute("status"))
            return '';

        $labelClass = 'label ';
        switch ($this->status)
        {
            case self::STATUS_ACTIVE:
                $labelClass .= 'label-success';
                break;

            case self::STATUS_BLOCK:
                $labelClass .= 'label-important';
                break;
            case self::STATUS_TRIAL:
                $labelClass .= '';
                break;

            default:
                break;
        }
        $labels = self::getArrayStatus();
        $label  = isset($labels[$this->status]) ? $labels[$this->status] : $this->status;
        return "<span class='$labelClass'>$label</span>";
    }

    public static function getCreateUrl($type)
    {
        return Yii::app()->createUrl(strtolower($type) . "/create");
    }

    public static function getImportUrl($type)
    {
        return Yii::app()->createUrl(strtolower($type) . "/import");
    }

    public static function getExportUrl($type)
    {
        $params = array();
        $key    = isset($_GET['key']) ? $_GET['key'] : '';
        if (isset($_GET['business']) && $_GET['business'])
        {
            $params['business'] = $_GET['business'];
        }
        if ($key)
        {
            $params['key'] = $key;
        }
        return Yii::app()->createUrl(strtolower($type) . "/export", $params);
    }

    public function getViewUrl()
    {
        return Yii::app()->createUrl(strtolower($this->type) . "/view", array(
                    "pk" => $this->ukey,
        ));
    }

    public function getBizProfileUrl($absolute = FALSE)
    {
        if ($this->business)
            if (strstr($this->business->biz_url, 'http') !== FALSE)
            {
                return $this->business->biz_url;
            }
            else
            {
                if ($absolute == FALSE)
                {
                    return Yii::app()->createUrl('frontend/default/index', array(
                                "biz" => $this->business->biz_url,
                    ));
                }
                else
                {
                    return Yii::app()->createAbsoluteUrl('frontend/default/index', array(
                                "biz" => $this->business->biz_url,
                    ));
                }
            }
        else
            return Yii::app()->createUrl('frontend/default/index', array(
                        "biz" => $this->ukey,
            ));
    }

    /**
     * Find a single active record with email
     * @param string $email
     * @return CActiveRecord
     */
    public static function getRecordByEmail($email)
    {
        return Users::model()->find('email=:email', array(':email' => $email));
    }

    /**
     * 
     * @param type $email
     * @param type $type
     * @return mixed <b>FALSE</b> if not exist and <b>a CActived Record</b> if otherwise
     */
    public static function check_exist_by_email($email, $type)
    {

        $cri = new CDbCriteria();

        $cri->compare('email', $email);
        $cri->compare('type', $type);

        $result = self::model()->find($cri);

        if ($result == NULL)
            return FALSE;


        return $result;
    }

    /**
     * Retrieves a model
     * @param string $ukey ukey of staff
     * @return CActiveData 
     */
    public static function getRecordByUkey($ukey)
    {
        return Users::model()->find('ukey=:ukey', array(':ukey' => $ukey));
    }

    public function getBookUrl()
    {
        return Yii::app()->createUrl("frontend/default/index", array(
                    "biz" => @$this->business->biz_url,
        ));
    }

    public function getEditUrl()
    {
        if ($this->id == self::SUPER_ADMIN)
            return FALSE;

        return Yii::app()->createUrl(strtolower($this->type) . "/edit", array(
                    "pk" => $this->ukey,
        ));
    }

    public function getDeleteUrl()
    {
        if ($this->id == self::SUPER_ADMIN)
            return FALSE;

        return Yii::app()->createUrl(strtolower($this->type) . "/delete", array(
                    "pk" => $this->ukey,
        ));
    }

    public function getChangePassUrl()
    {
        if ($this->type == self::TYPE_BUSINESS)
        {
            return Yii::app()->createUrl('profileBiz/changePassword');
        }
        else
        {
            return Yii::app()->createUrl('profile/changePassword');
        }
    }

    public function getChangeEmailUrl()
    {
        if ($this->type == self::TYPE_BUSINESS)
        {
            return Yii::app()->createUrl('profileBiz/changeEmail');
        }
        else
        {
            return Yii::app()->createUrl('profile/changeEmail');
        }
    }

    /**
     * return ukey, name, status of merchant
     */
    public static function get_merchant()
    {
        $crite            = new CDbCriteria();
        $crite->select    = 'status,type, ukey, business_name';
        $crite->condition = 'type=:t';
        $crite->params    = array(':t' => self::TYPE_BUSINESS);

        $biz = self::model()->findAll($crite);

        $arry = array();
        if ($biz)
        {
            foreach ($biz as $value)
            {
                $arry[] = array(
                    'biz_ukey' => $value->ukey,
                    'biz_name' => $value->business_name,
                    'status'   => $value->status
                );
            }

            return $arry;
        }
        else
        {
            return FALSE;
        }
    }

//    public static function getAllM
    /**
     * 
     * @param boolean $ukey 
     * <b>TRUE</b> return list of ukey biz <br>
     * <b>FALSE</b> return list of id biz <br>
     * @return array list of ukey or id of biz <br>
     * An empty array returned if none is found.
     */
    public static function getAllBussiness($ukey = FALSE, $parent = 0, $parentget = false)
    {
        $crite            = new CDbCriteria();
        $crite->select    = 'id, type, ukey, business_name';
        $crite->order     = 'business_name ASC';
        $crite->condition = 'type=:t';
        $crite->params    = array(':t' => self::TYPE_BUSINESS);
        if ($parent > 0)
            if ($parentget == false)
                $crite->addCondition('author_id = ' . $parent);
            else
                $crite->addCondition('(author_id = ' . $parent . ' OR id=' . $parent . ')');
        $bizs             = self::model()->findAll($crite);
        $ret              = array();

        //update for staff does not belong to any merchant
//        $ret[''] = 'Select Merchant...';

        foreach ($bizs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[$biz->ukey] = $biz->business_name;
            }
            else
            {
                $ret[$biz->id] = $biz->business_name;
            }
        }

        return $ret;
    }

    public static function getAllBussinessUkey($id = FALSE)
    {
        $bizs = self::model()->findAll("type=:t", array(
            ':t' => self::TYPE_BUSINESS
        ));
        $ret  = array();

        foreach ($bizs as $biz)
        {
            if ($id == TRUE)
            {
                $ret[] = $biz->id;
            }
            else
            {
                $ret[] = $biz->ukey;
            }
        }

        return $ret;
    }

    /**
     * 
     * @return array <b>id</b> staff
     */
    public static function getAllStaff($ukey = FALSE)
    {
        $bizs = self::model()->findAll("type=:t", array(
            ':t' => self::TYPE_STAFF
        ));
        $ret  = array();
        foreach ($bizs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[$biz->ukey] = $biz->name;
            }
            else
            {
                $ret[$biz->id] = $biz->name;
            }
        }

        return $ret;
    }

    /**
     * Get all staff of the merchant
     * @return mixed Description
     */
    public function get_all_staff_id_of_merchant()
    {

        $criteria         = new CDbCriteria();
        $criteria->select = array('author_id', 'id', 'type');
        $criteria->compare('type', Users::TYPE_BUSINESS);
        $criteria->compare('author_id', $this->id);

        $list_merchant = Users::model()->findAll($criteria);

        $arr_merchant   = array();
        $arr_merchant[] = $this->id;

        if ($list_merchant)
        {
            foreach ($list_merchant as $m)
            {
                $arr_merchant[] = $m->id;
            }
        }

        $crite2         = new CDbCriteria();
        $crite2->addInCondition('author_id', $arr_merchant);
        $crite2->select = array('id', 'author_id', 'ukey', 'type');
        $crite2->compare('type', Users::TYPE_STAFF);

        $list_staff = Users::model()->findAll($crite2);

        if ($list_staff)
        {

            $arr_list_staff = array();

            foreach ($list_staff as $staff)
            {
                $arr_list_staff[$staff->ukey] = $staff->id;
            }

            return $arr_list_staff;
        }
        else
        {
            return array();
        }
    }

    /**
     * 
     * @return array <b>id</b> staff
     */
    public static function getAllStaffAndBiz($ukey = FALSE)
    {
        $bizs = self::model()->findAll("type=:t", array(
            ':t' => self::TYPE_STAFF
        ));
        $ret  = array();
        foreach ($bizs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[] = array(
                    'id'    => $biz->ukey,
                    'name'  => $biz->name,
                    'group' => $biz->author->name
                );
            }
            else
            {
                $ret[] = array(
                    'id'    => $biz->id,
                    'name'  => $biz->name,
                    'group' => $biz->author->name
                );
            }
        }

        return $ret;
    }

    /**
     * 
     * @return array list of id bussiness
     * an empty array is returned if none is found
     */
    public static function getAllStaffOfBusiness($id_bussiness = NULL, $ukey = FALSE)
    {
        if ($id_bussiness == NULL)
            $id_bussiness = Yii::app()->user->id;

        if ($ukey === TRUE)
        {
            $user = Users::model()->find('ukey=:u', array(':u' => $id_bussiness));
            if ($user != NULL)
            {
                $id_bussiness = $user->id;
            }
        }

        $bizs = self::model()->findAll("type=:t AND author_id=:a AND status=:status", array(
            ':t'      => self::TYPE_STAFF,
            ':a'      => $id_bussiness,
            ':status' => self::STATUS_ACTIVE
        ));
        $ret  = array();
        foreach ($bizs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[$biz->ukey] = $biz->name;
            }
            else
            {
                $ret[$biz->id] = $biz->name;
            }
        }

        return $ret;
    }

    /**
     * 
     * @param type $ukey id or ukey of bessness
     * @return array list of staff user
     */
    public static function getStaffByBusinessUkey($ukey, $is_ukey = FALSE)
    {

        if ($is_ukey)
        {
            $user   = Users::model()->find('ukey=:u', array(':u' => $ukey));
            $biz_id = $user->id;
        }
        else
        {
            $biz_id = $ukey;
        }

        $staff = self::model()->findAll("type=:t AND author_id=:a AND status=:status", array(
            ':t'      => self::TYPE_STAFF,
            ':a'      => $biz_id,
            ':status' => Users::STATUS_ACTIVE
        ));

        return $staff;
    }

    /**
     * @param boolean $ukey 
     * <b>TRUE</b> get by ukey and return list of ukey staff <br>
     * <b>FALSE</b> get by id  and return list of id staff   <br>             
     * @param type $id_bussiness id or ukey of biz
     * @return array list of ukey or id staff.  <br>
     * An empty array is returned if none is found.
     */
    public static function getAllStaffByBusiness($id_bussiness, $ukey = FALSE)
    {
        $crite         = new CDbCriteria();
        $crite->select = array('ukey', 'type', 'status', 'id');


        if ($ukey === TRUE)
        {
            $crite->compare('ukey', $id_bussiness);

            $staff = Users::model()->find($crite);

            if ($staff != NULL)
            {
                $id_bussiness = $staff->id;
            }
            else
            {
                //can not find 

                return array();
            }
        }

        $crite2            = new CDbCriteria();
        $crite2->select    = array('ukey', 'type', 'status', 'id', 'business_name', 'firstname', 'lastname');
        $crite2->condition = "type=:t AND author_id=:a AND status=:status";
        $crite2->params    = array(
            ':t'      => self::TYPE_STAFF,
            ':a'      => $id_bussiness,
            ':status' => Users::STATUS_ACTIVE);


        $bizs = self::model()->findAll($crite2);

        if (empty($bizs))
        {
            return array();
        }

        $ret = array();

        foreach ($bizs as $biz)
        {
            if ($ukey == TRUE)
            {
                $ret[$biz->ukey] = $biz->name;
            }
            else
            {
                $ret[$biz->id] = $biz->name;
            }
        }

        return $ret;
    }

    public static function getUserServiceByID($id_user)
    {
        $model = Users::model()->findByPk($id_user);

        if ($model == NULL)
        {
            return FALSE;
        }
        else
        {
            if ($model->type == Users::TYPE_ADMIN)
            {
                return Users::TYPE_ADMIN;
            }
            if ($model->type == Users::TYPE_BUSINESS)
            {
                return $id_user;
            }
            if ($model->type == Users::TYPE_STAFF)
            {
                return $model->author_id;
            }
        }
    }

    public static function getUserNoteByID($id_user)
    {
        $model = Users::model()->findByPk($id_user);
        if ($model == Null)
        {
            return FALSE;
        }
        else
        {

            if ($model->type == Users::TYPE_ADMIN)
            {
                return Users::TYPE_ADMIN;
            }
            else
            {
                $arr = array();
                if ($model->type == Users::TYPE_BUSINESS)
                {
                    $arr[0]    = $id_user;
                    $all_staff = Users::getAllStaffByBusiness($id_user);
                    foreach ($all_staff as $k => $value)
                    {
                        $arr[$k] = $k;
                    }
                    return $arr;
                }
                else
                {
                    //find biz
                    $all_staff = Users::getAllStaffByBusiness($model->author_id);
                    $arr[0]    = $model->author_id;

                    foreach ($all_staff as $k => $value)
                    {
                        $arr[$k] = $k;
                    }

                    return $arr;
                }
            }
        }
    }

    /**
     * @return array list of id staff satisfying  the specified condition.
     * An empty array is returned if none is found
     * if <b>Admin</b>  return all id
     * if <b>Bussiness</b> return all id staff of itself
     */
    public static function getAllChildByID($id_user)
    {
        $model = Users::model()->findByPk($id_user);

        $arr = array();

        if ($model == NULL)
        {
            return $arr;
        }
        else
        {
            $arr[$id_user] = $id_user;
            if ($model->type == Users::TYPE_ADMIN)
            {
                $sff = $model->getAllStaff();

                foreach ($sff as $k => $v)
                {
                    $arr[$k] = $k;
                }
                return $arr;
            }

            if ($model->type == Users::TYPE_BUSINESS)
            {
                $sff = $model->getAllStaffOfBusiness();
                foreach ($sff as $k => $v)
                {
                    $arr[$k] = $k;
                }
                return $arr;
            }

            if ($model->type == Users::TYPE_STAFF)
            {

                return $arr;
            }
        }
    }

    public function getName()
    {
        if ($this->type == self::TYPE_BUSINESS)
        {
            return $this->business_name;
        }
        else
        {
            return "$this->firstname $this->lastname";
        }
    }

    function genUkey()
    {
        // Prefix của ukey
        $uKeyPrefix = self::getUkeyPrefix();
        $prefix     = $uKeyPrefix[$this->type];

        // Chuỗi số của ukey
        $result = crc32($this->id);
        if ($result < 0)
        {
            $result = '0' . abs($result);
        }
        $ukey = trim(sprintf("%012d", $result));

        return "$prefix-$ukey";
    }

    function updateUkey()
    {
        $this->ukey = $this->genUkey();
        $this->update(array('ukey'));
    }

    /**
     * @return array list of ukey staff or list of id depen on $ukey
     */
    public static function getAllStaffUkeyByBizUkey($biz_id, $ukey = TRUE)
    {
        $staff = Users::model()->findAll('author_id=:biz_id AND status=:status', array(
            ':biz_id' => $biz_id,
            ':status' => Users::STATUS_ACTIVE
        ));
        $arr   = array();
        if ($staff == NULL)
        {
            return $arr;
        }
        else
        {
            foreach ($staff as $key => $value)
            {
                if ($ukey)
                {
                    $arr[] = $value->ukey;
                }
                else
                {
                    $arr[] = $value->id;
                }
            }

            return $arr;
        }
    }

    /**
     * @return array array of customer note or <b> FALSE </b> if empty
     */
    function getAllNoteByUkey($ukey)
    {
        $criteria        = new CDbCriteria();
        $criteria->order = 'date DESC';

        $checkuser = Users::model()->findByPk(Yii::app()->user->id);
        $id_cus    = Users::getIdByUkey($ukey);

        //if admin
        if ($checkuser->type == Users::TYPE_ADMIN && $id_cus != NULL)
        {
            $criteria->condition = 'customer_id=:cus_id';

            $criteria->params = array(':cus_id' => $id_cus);
            $model            = CustomerNote::model()->findAll($criteria);
        }
        else
        { //if biz or staff
            $list_user = Users::getAllChildByID(Yii::app()->user->id);

            $criteria->addInCondition('author', $list_user);
            $criteria->condition = 'customer_id=:cus_id';
            $criteria->params    = array(':cus_id' => $id_cus);

            $model = CustomerNote::model()->findAll($criteria);
        }


        if ($model == NULL)
        {
            return FALSE;
        }
        else
        {
            $arr = array();
            foreach ($model as $v)
            {
                $arr[] = array(
                    'date' => date('D, d M, Y', $v->date),
                    'note' => $v->note_content
                );
            }
            return $arr;
        }
    }

    static function getUkeyPrefix()
    {
        return array(
            self::TYPE_ADMIN     => self::PREFIX_ADMIN,
            self::TYPE_BUSINESS  => self::PREFIX_BUSINESS,
            self::TYPE_STAFF     => self::PREFIX_STAFF,
            self::TYPE_CUSTOMER  => self::PREFIX_CUSTOMER,
            self::TYPE_CONCIERGE => self::PREFIX_CONCIERGE
        );
    }

    /**
     * 
     * @param string $ukey
     * @return mixed return id of user or <b>FALSE</b> if otherwise
     */
    public static function getIdByUkey($ukey)
    {
        $criteria            = new CDbCriteria();
        $criteria->select    = array('id', 'ukey');
        $criteria->condition = 'ukey=:u';
        $criteria->params    = array(':u' => $ukey);

        $user = self::model()->find($criteria);

        if ($user != NULL)
            return $user->id;
        else
            return FALSE;
    }

    static function getUkeyById($id)
    {
        $user = self::model()->find('id=:id', array(
            ':id' => $id,
        ));

        if ($user != NULL)
            return $user->ukey;
        else
            return NULL;
    }

    function updateRole()
    {
        $auth = Yii::app()->authManager;

        // Xóa các quy�?n đã gán trước đây đi
        if ($auth->getAuthAssignments($this->id))
            foreach ($auth->getAuthAssignments($this->id) as $item)
                $auth->revoke($item->itemName, $this->id);

        // Gán quy�?n mới vào
        $auth->assign($this->type, $this->id);
    }

    /**
     * Find a single record of Business owner by ukey staff
     * @param string $staff_ukey
     * @return CActiveRecord a single record of model
     */
    public static function getBizbyUkeyStaff($staff_ukey)
    {
        $user      = Users::model()->find('ukey=:ukey', array(':ukey' => $staff_ukey));
        $biz_model = Users::model()->findByPk($user->author_id);
        return $biz_model;
    }

    /**
     * @param int $staff_id id of staff
     * @return int id of my biz or <b>FALSE</b> if otherwise
     */
    public static function getMyBiz($staff_id)
    {
        $criteria            = new CDbCriteria();
        $criteria->select    = array('id,author_id');
        $criteria->condition = 'id=:id';
        $criteria->params    = array('id' => $staff_id);

        $biz = Users::model()->find($criteria);

        if ($biz == NULL)
        {
            return FALSE;
        }
        else
        {
            return $biz->author_id;
        }
    }

    function completeCreateUser()
    {
        if (!$this->type)
            return FALSE;

        $this->updateUkey();
        $this->updateRole();

        return TRUE;
    }

    public function formartDate()
    {
        echo date('F d Y', $this->date_created);
    }

    public function getFullAddress()
    {
        return "$this->address  $this->country $this->postal_code";
    }

    public function getAddressCustomerBelongUser()
    {
        foreach ($this->customers as $cus)
        {
            $location = $cus->address . ' ' . $cus->city . ' ' . $cus->country;
            if ($location != '  ')
            {
                return $location;
                break;
            }
        }
    }

    public function getCheckinCount()
    {
        if ($this->facebook != '' & $this->type == Users::TYPE_BUSINESS)
        {

            preg_match_all('!\d+!', $this->facebook, $match);
            $id_page = $match[0][0];
            $s       = curl_init();
            curl_setopt($s, CURLOPT_URL, 'https://graph.facebook.com/' . $id_page);
            curl_setopt($s, CURLOPT_USERAGENT, 'voithan.com');
            curl_setopt($s, CURLOPT_HTTPGET, TRUE);
            curl_setopt($s, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($s, CURLOPT_REFERER, 'http://webmaster.com.sg');
            curl_setopt($s, CURLOPT_HEADER, FALSE);

            $output       = curl_exec($s);
            $code_reponse = curl_getinfo($s, CURLINFO_HTTP_CODE);

            if ($code_reponse == 200)
            {
                $array = json_decode($output);

                return $array->checkins;
                curl_close($s);
            }
            else
            {
                return FALSE;
            }
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * 
     * @return string duong dan anh
     */
    public function getImagebooking()
    {

        if (isset($this->gallery[0]))
        {
            return $this->gallery[0]->getPublicImageXY(400, 225);
        }
        else
        {
            if (isset($this->business->book_bg))
            {

                return $this->business->getBookBG();
            }
            else
            {
                return Yii::app()->controller->assetDir . '/img/no-image.png';
            }
        }
    }

    /**
     * Lay tong so rating cac service cua merchant.
     * Hien thi tai trang profile
     * @return mixed NULL if not found and a float if otherwise
     */
    public function getVoteTimes()
    {

        if (!$this->services)
            return 0;

        $count_vote = 0;
        foreach ($this->services as $sv)
        {
            if ($sv->allReviewCount())
            {
                $count_vote+=$sv->allReviewCount();
            }
        }

        return $count_vote;
    }

    public function getAvgVote()
    {
        if (!$this->services)
            return 0;

        $avg_rating    = 0;
        $count_service = 0;
        foreach ($this->services as $sv)
        {
            if ($sv->getAverageReviewPoint())
            {
                $avg_rating += floatval($sv->getAverageReviewPoint());
                $count_service+=1;
            }
        }
        if ($count_service == 0)
            return 0;

        return ceil(($avg_rating / $count_service ) * 2) / 2;
    }

    /**
     * put your comment there...
     * 
     */
    public function getAvrPoint()
    {
        return NULL;
    }

    /**
     * @webmaster: have to fix this
     * @return null
     */
    public function getGroup()
    {
        $staff_group = GroupUser::model()->find('user_id=' . $this->id);

        if ($staff_group AND $staff_group->group_info != NULL)
        {
            return $staff_group->group_info->name;
        }
        else
        {
            return NULL;
        }
    }

    /**
     * Use this function at profile merchant
     * @return mixed <b>FALSE</b> if not found service or a CActiveRecord
     */
    public function getServices()
    {
        $cri = new CDbCriteria();

        $cri->with      = array('user', 'category');
//        $cri->condition = 't.author_id=:uid AND user.status=:status AND t.type=:type AND book_online>0 AND t.price>0 AND category.isshow!=:show';
        $cri->condition = 't.author_id=:uid AND t.type=:type AND book_online>0';
        $cri->order     = "weight DESC, s_name ASC";
        $cri->params    = array(
            ':uid'  => $this->id,
            ':type' => Service::TYPE_SERVICE,
//            ':show' => Category::HIDDEN
        );

        $services = Service::model()->findAll($cri);

        if ($services)
        {
            return $services;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * put your comment there...
     * 
     */
    public function getRooms()
    {
        $cri            = new CDbCriteria();
        $cri->with      = array('service');
        $cri->condition = 'service.author_id=:u AND t.type=:t AND t.date>:d AND service.book_online>0 AND service.price>0';
        $cri->params    = array(
            ':u' => $this->id,
            ':t' => Appoint::TYPE_ROOM,
            ':d' => Utils::getResetTimeStamp(time())
        );
        $cri->with      = array('service', 'service.user', 'service.category');
        $cri->compare('user.status', Users::STATUS_ACTIVE);
        $cri->compare('category.isshow', Category::SHOW_HOMEPAGE);
        $appoint        = Appoint::model()->findAll($cri);

        if ($appoint)
        {
            return $appoint;
        }
        else
        {
            return FALSE;
        }
    }

    public function getCountFavour()
    {
        $favourites = Favourite::model()->findAll('biz_id=:s', array(
            ':s' => $this->id
        ));
        if ($favourites)
        {
            return count($favourites);
        }
        else
        {
            return FALSE;
        }
    }

    public static function countUser($type)
    {
        $current_user = self::getCurrentUser();

        $cri            = new CDbCriteria();
        $cri->condition = 'type=:ty and status=:st';

        if ($current_user->type == Users::TYPE_BUSINESS OR $current_user->type == Users::TYPE_STAFF)
        {
            $cri->addCondition('author_id=' . Yii::app()->user->getId());
        }

        $cri->params = array(
            ':ty' => $type,
            ':st' => Users::STATUS_ACTIVE,
        );

        return self::model()->count($cri);
    }

    public function getLogoImage130()
    {
        $file = Yii::getPathOfAlias('webroot') . '/' . $this->photo;

        if (is_file($file) && $this->photo != NULL)
        {
            list($w) = getimagesize($file);
            $percent    = ceil(130 / $w * 100);
            $dir_name   = dirname($file);
            $path_parts = pathinfo($file);
            $extesion   = $path_parts['extension'];

            $file_name = $path_parts['filename'] . "_w130." . $extesion;

            if (!file_exists($dir_name . '/' . $file_name) OR ! is_file($dir_name . '/' . $file_name))
            {
                $thumb = Yii::app()->phpThumb->create($file);
                $thumb->resizePercent($percent);
                $thumb->save($dir_name . '/' . $file_name);
                return Yii::app()->baseUrl . '/files/user' . '/' . $file_name;
            }
            else
            {
                return Yii::app()->baseUrl . '/files/user' . '/' . $file_name;
            }
        }
        return Yii::app()->controller->assetDir . '/img/avatar-blank.jpg';
    }

    public static function get_all_merchant($returnName = FALSE, $include_first = FALSE)
    {
        $model = Users::model()->findAll('type=:i', array(
            ':i' => self::TYPE_BUSINESS));

        $arr = array();

        if ($include_first)
        {
            $arr[] = 'Choose one (Merchant)';
        }

        foreach ($model as $merchant)
        {
            if (!$returnName)
            {
                $arr[$merchant->id] = $merchant->business_name;
            }
            else
            {
                $arr[] = $merchant->business_name;
            }
        }

        return $arr;
    }

    public static function GetAllMerchant($returnName = FALSE, $include_first = FALSE)
    {
        $model = Users::model()->findAll('type=:i AND status=:status', array(
            ':i'      => self::TYPE_BUSINESS,
            ':status' => self::STATUS_ACTIVE));

        $arr = array();

        if ($include_first)
        {
            $arr[] = 'Choose one';
        }

        foreach ($model as $merchant)
        {
            if (!$returnName)
            {
                $arr[$merchant->id] = $merchant->business_name;
            }
            else
            {
                $arr[] = $merchant->business_name;
            }
        }

        return $arr;
    }

    //Only for check merchant is branch
    public function getIsBranch()
    {
        if ($this->author_id != Users::SUPER_ADMIN)
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }

    //Get Request Booking for My Account
    public function getRequestBooking()
    {
        $query           = 'select tbl_request_booking.*,tbl_users.business_name from tbl_request_booking JOIN tbl_customer JOIN tbl_users ON tbl_customer.id = tbl_request_booking.customer_id AND tbl_users.id = tbl_request_booking.merchant_id WHERE tbl_customer.user_id = ' . Yii::app()->user->getId() . ' ORDER BY tbl_request_booking.rid DESC';
        $request_booking = Yii::app()->db->createCommand($query)->queryAll();
        return $request_booking;
    }

    /**
     * @uses at Customer.php
     * @return mixed <b>FALSE</b> if not found and id of user if otherwise
     */
    public static function is_exist($email, $type)
    {

        $criteria         = new CDbCriteria();
        $criteria->select = array('id', 'email', 'type');
        $criteria->compare('email', $email);
        $criteria->compare('type', $type);

        $use = self::model()->find($criteria);

        if ($use)
        {
            return $use->id;
        }
        else
        {
            return FALSE;
        }
    }

    /**
     * Get all available reviews of service under an biz user
     * @return mixed <b>FALSE</b> if not found reviews or a CActiveRecord
     */
    public function getServiceReviews()
    {
        $cri = new CDbCriteria();

        $services = $this->getServices();

        //No service , no reviews, return
        if ($services == null)
            return false;
        /**
         * var $service Service
         */
        foreach ($services as $service)
        {
            $sidArr[] = $service->sid;
        }
        //$cri->compare('status', Review::STATUS_ACTIVE);
        $cri->addInCondition('sid', array_values($sidArr));
        $cri->order     = 'date DESC';
        $servicesReview = Review::model()->findAll($cri);

        if ($servicesReview)
        {
            return $servicesReview;
        }
        else
        {
            return FALSE;
        }
    }

    public function getIsAdmin()
    {
        if ($this->type == self::TYPE_ADMIN)
            return true;
        else
            return false;
    }

    public function getIsBussiness()
    {
        if ($this->type == self::TYPE_BUSINESS)
            return true;
        else
            return false;
    }

    public function getIsStaff()
    {
        if ($this->type == self::TYPE_STAFF)
            return true;
        else
            return false;
    }

    public function getIsCustomer()
    {
        if ($this->type == self::TYPE_CUSTOMER)
            return true;
        else
            return false;
    }

    public function getPercent()
    {
        if (isset($this->business->payment_percent) && floatval($this->business->payment_percent) > 0 && floatval($this->business->payment_percent) <= 100)
            return (float) $this->business->payment_percent;
        else
            return self::PAYMENT_PERCENT;
    }

    /**
     * get url $v->business->biz_url
     * name merchant $v->business_name
     * name cate $v->merchantCats -> foreach $v2->category->name
     * @return mixed <b>FALSE</b> if has no branch, or <b> list of url and name of branch 
     */
    public function get_my_branch()
    {

        $criteria = new CDbCriteria();

        $criteria->select    = array('business_name', 'id', 'business_logo', 'address', 'photo');
        $criteria->condition = 'type=:t AND author_id=:author_id';
        $criteria->params    = array(':t' => Users::TYPE_BUSINESS, 'author_id' => $this->id);

        $find_my_branch = $this->model()->findAll($criteria);

        if (empty($find_my_branch))
        {
            return FALSE;
        }
        else
        {
            return $find_my_branch;
        }
    }

    /**
     * Get all brach of merchant
     * @param int $id id of merchant 
     * @return mixed <b>FALSE</b> if not found or list of id branch
     */
    public static function get_my_branch_by_id($id)
    {

        $crite            = new CDbCriteria();
        $crite->select    = array('id', 'author_id', 'type');
        $crite->condition = 'author_id=' . $id;
        $crite->compare('type', Users::TYPE_BUSINESS);

        $list_branch = Users::model()->findAll($crite);

        if (NULL == $list_branch)
        {
            return FALSE;
        }
        else
        {

            $arr_reponse = array();

            foreach ($list_branch as $key => $value)
            {
                $arr_reponse[] = $value->id;
            }

            return $arr_reponse;
        }
    }

    public function get_customer_id()
    {
        
    }

    /**
     * Get Current notification of current user
     * @return int
     */
    public function getNotCount()
    {
        $number = 0;
        if ($this->type == Users::TYPE_ADMIN)
        {
            $countNewContactMessage = Contact::model()->countByAttributes(array('status' => Contact::STATUS_NEW));
            if ($countNewContactMessage > 0)
                $number                 = $number + intval($countNewContactMessage);
        }
        return $number;
    }

    /**
     * Get badges message
     * @return string
     */
    public function getBadgeMessage()
    {
        if ($this->getNotCount() > 0)
            return '<span class="badge badge-important">' . $this->getNotCount() . ' new</span>';
        return '';
    }

    /**
     * @return mixed List of id business, branch of user loged in or <b>empty array</b>
     * if user is guest
     */
    public static function get_all_branch_id_of_user_logedin()
    {
        if (Yii::app()->user->isGuest)
        {
            return array();
        }
        else
        {

            if (Yii::app()->user->isStaff())
            {

                //find it's merchant
                //Get CACtive model of user logged
                $crr_user = Yii::app()->user->getCurrentUser();

                //find it's merchant
                $parent_of_staff = Users::model()->findByPk($crr_user->author_id);

                //if can not find merchant
                if (NULL === $parent_of_staff)
                {

                    return array();
                }
                else
                {

                    //if merchant is branch
                    if ($parent_of_staff->getIsBranch())
                    {

                        //find main merchant
                        $main_merchant = Users::model()->findByPk($parent_of_staff->author_id);

                        //if not found
                        if (NULL === $main_merchant)
                        {
                            return array($parent_of_staff->id);
                        }
                        else
                        {

                            //find all branch
                            $branches = Users::get_my_branch_by_id($main_merchant->id);

                            if (FALSE == $branches)
                            {
                                return array($main_merchant->id);
                            }
                            else
                            {

                                $branches[] = $main_merchant->id;

                                return $branches;
                            }
                        }
                    }

                    if ($parent_of_staff->getIsBussiness())
                    {


                        $branches = Users::get_my_branch_by_id($parent_of_staff->id);


                        if (FALSE == $branches)
                        {
                            return array($parent_of_staff->id);
                        }
                        else
                        {

                            $branches[] = $parent_of_staff->id;

                            return $branches;
                        }
                    }
                }
            }

            if (Yii::app()->user->isMerchant())
            {

                $crr_user = Yii::app()->user->getCurrentUser();

                //find branch
                $branches = Users::get_my_branch_by_id($crr_user->id);

                if (FALSE == $branches)
                {
                    return array($crr_user->id);
                }
                else
                {

                    $branches[] = $crr_user->id;

                    return $branches;
                }
            }

            if (Yii::app()->user->isBranch())
            {

                $crr_user = Yii::app()->user->getCurrentUser();

                //find main merchant
                $main_merchant = Users::model()->findByPk($crr_user->author_id);

                //if not found
                if (NULL === $main_merchant)
                {
                    return array($crr_user->id);
                }
                else
                {

                    //find all branch
                    $branches = Users::get_my_branch_by_id($main_merchant->id);

                    if (FALSE == $branches)
                    {
                        return array($main_merchant->id);
                    }
                    else
                    {

                        $branches[] = $main_merchant->id;

                        return $branches;
                    }
                }
            }
        }
    }

    /**
     * @param boolean $merchant_id <b>TRUE</b> if find by id, otherwise find by ukey
     * @return mixed all id of branch
     */
    public static function get_id_all_branch($merchant_ukey, $merchant_id = FALSE)
    {
        if ($merchant_id)
            $merchant = self::model()->findByPk($merchant_ukey);
        else
            $merchant = Users::getRecordByUkey($merchant_ukey);

        if (NULL == $merchant)
        {
            return NULL;
        }
        else
        {

            $arr_merchant_id = array();

            //if merchant is branch, get parent merchant
            if ($merchant->getIsBranch())
            {

                //get parent 
                $parent = $merchant->getParent;

                if ($parent)
                {

                    $arr_merchant_id[] = $parent->id;
                    //get all branch
                    $branchs           = $parent->get_my_branch();

                    if ($branchs)
                    {
                        foreach ($branchs as $b)
                        {

                            //assign 
                            $arr_merchant_id[] = $b->id;
                        }
                    }
                }

                return $arr_merchant_id;
            }

            $arr_merchant_id[] = $merchant->id;

            $branchs = $merchant->get_my_branch();

            if ($branchs)
            {
                foreach ($branchs as $b)
                {

                    //assign 
                    $arr_merchant_id[] = $b->id;
                }
            }

            return $arr_merchant_id;
        }
    }

    public static function get_all_merchant_for_frontend()
    {
        $query_sql = 'SELECT tbl_users.id,tbl_users.business_name,tbl_business.biz_url as merchant_url FROM tbl_users JOIN tbl_business ON tbl_users.id = tbl_business.user_id WHERE tbl_users.type = "BizUser" AND tbl_users.id NOT IN (6,6227,6230,6233,6234,6235,6237,6238,6329,6184) order by tbl_users.business_name ASC';

        $command = Yii::app()->db->cache(2000)->createCommand($query_sql)->queryAll();

        $arr = array('' => Yii::t('main', 'Select Merchant'));
        if ($command != NULL)
        {
            foreach ($command as $merchant)
            {
                if ($merchant['merchant_url'] != FALSE)
                    $arr[$merchant['merchant_url']] = $merchant['business_name'];
            }
        }
        return $arr;
    }

    public static function getMerchantUrl($mid)
    {
        $merchant_url = Yii::app()->db->createCommand("SELECT biz_url from `tbl_business` where user_id=$mid")->queryAll();
        if ($merchant_url != NULL && $merchant_url[0]['biz_url'] != '')
            return $merchant_url[0]['biz_url'];
        else
            return FALSE;
    }

}
